package me.helllp.bootman.back.config.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;


/**
 * Shiro Manager 配置
 * 
 * @author 虎头
 *
 */
public class ShiroManager {
	/**
	 * 保证实现了Shiro内部lifecycle函数的bean执行
	 */
	@Bean(name = "lifecycleBeanPostProcessor")
	@ConditionalOnMissingBean
	public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
		return new LifecycleBeanPostProcessor();
	}

	/**
	 * 自定义redisCachemanager
	 * 
	 */
	@Bean(name = "shiroCacheManager")
	@ConditionalOnMissingBean
	public CacheManager cacheManager() {
		return new RedisCacheManager();
	}

	@Bean(name = "securityManager")
	@ConditionalOnMissingBean
	public DefaultSecurityManager securityManager(CacheManager shiroCacheManager) {
        DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager();

        // 用自己的Factory实现替换默认
        // 用于关闭session功能
        dwsm.setSubjectFactory(new BootmanSubjectFactory());
        dwsm.setSessionManager(sessionManager());
        // 关闭session存储
        ((DefaultSessionStorageEvaluator) ((DefaultSubjectDAO)dwsm.getSubjectDAO()).getSessionStorageEvaluator()).setSessionStorageEnabled(false);

//      <!-- 用户授权/认证信息Cache, 采用Redis 缓存 -->
        dwsm.setCacheManager(shiroCacheManager);

        SecurityUtils.setSecurityManager(dwsm);
        return dwsm;
	}

    private DefaultWebSessionManager sessionManager() {
    	DefaultWebSessionManager manager = new DefaultWebSessionManager();
        // 关闭session定时检查
        manager.setSessionValidationSchedulerEnabled(false);

        return manager;
    }

	@Bean
	@ConditionalOnMissingBean
	public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(DefaultSecurityManager securityManager) {
		AuthorizationAttributeSourceAdvisor aasa = new AuthorizationAttributeSourceAdvisor();
		aasa.setSecurityManager(securityManager);
//		org.apache.shiro.authc.pam.AllSuccessfulStrategy b = new org.apache.shiro.authc.pam.AllSuccessfulStrategy();
//		org.apache.shiro.authc.pam.ModularRealmAuthenticator a = new org.apache.shiro.authc.pam.ModularRealmAuthenticator();
//		a.setAuthenticationStrategy(b);
		return aasa;
	}
}
